package com.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @BelongsProject: LeetCode
 * @BelongsPackage: com.leetcode
 * @Author: lei
 * @CreateTime: 2024-04-01  09:12
 * @Description: TODO
 * @Version: 1.0
 */
public class 螺旋矩阵 {
    public static void main(String[] args) {
        //int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
        int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}, {17, 18, 19, 20}};
        List<Integer> result = spiralOrder(matrix);
        Integer[] integers = result.toArray(new Integer[0]);
        System.out.println(Arrays.toString(integers));
    }

    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> resultList = new ArrayList<>();
        int row = 0, rowLength = matrix.length - 1;
        int column = 0, columnLength = matrix[0].length - 1;
        while (true) {
            // 从左到右进行计算
            for (int i = column; i <= columnLength; i++) {
                int current = matrix[row][i];
                resultList.add(current);
            }

            // 从上到下进行计算
            if (++row > rowLength) break;
            for (int i = row; i <= rowLength; i++) {
                int current = matrix[i][columnLength];
                resultList.add(current);
            }

            // 从右到左进行计算
            if (--columnLength < column) break;
            for (int i = columnLength; i >= column; i--) {
                int current = matrix[rowLength][i];
                resultList.add(current);
            }

            if (--rowLength < row) break;
            for (int i = rowLength; i >= row; i--) {
                int current = matrix[i][column];
                resultList.add(current);
            }

            if (++column > columnLength) break;
        }
        return resultList;
    }
}
